﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VisionFrame.Base;

namespace ImageCapture
{
    /// <summary>
    /// 通信目录进行图像加载
    /// </summary>
    public class FolderImageNodeModel : NodeModelBase
    {
        public FolderImageNodeModel()
        {
            this.NodeName = "图像加载(F)";

            this.Arguments.Add(new VisionFrame.Base.Models.NodeArgModel
            {
                ArgName = "图像目录",
                ArgType = "String",
                Direction = "输入",
                ValueMode = 2
            });
            this.Arguments.Add(new VisionFrame.Base.Models.NodeArgModel
            {
                ArgName = "图像Handle",
                ArgType = "IntPtr",
                Direction = "输出"
            });
            this.Arguments.Add(new VisionFrame.Base.Models.NodeArgModel
            {
                ArgName = "测试",
                ArgType = "IntPtr",
                Direction = "输出",
                ValueMode = 1
            });
        }
        int index = 0;
        public override void Execute(IFlowContext flowContext)
        {
            // 对接输入参数
            if (this.Arguments[0].ArgValue == null)
                throw new Exception("图像目录参数未配置");
            if (this.Arguments[1].ArgValue == null)
                throw new Exception("图像Handle参数未配置");

            string folder = this.Arguments[0].ArgValue.ToString();

            if (!Directory.Exists(folder))
                throw new Exception("图像目录未找到");

            string[] files = Directory.GetFiles(folder, "*.bmp");
            if (files.Length == 0)
                throw new Exception("未发现图像文件");

            IntPtr handle = new Bitmap(files[index]).GetHbitmap();
            

            // 对接输入参数 --- FlowTab中的参数名称
            //this.Arguments[1].ArgValue

            var am = flowContext.ArgumentList
                .FirstOrDefault(a => a.ArgName == this.Arguments[1].ArgValue.ToString());

            if (am.ArgType != this.Arguments[1].ArgType)
                throw new Exception("参数配置异常！类型不匹配");

            am.Value = handle;

            index++;
            if (index >= files.Length)
                index = 0;

        }
    }
}
